package com.example.cdctestsystem.controller;

import com.example.cdctestsystem.pojo.UserInfo;
import com.example.cdctestsystem.service.UserInfoService;
import com.example.cdctestsystem.util.CookieUtil;
import com.example.cdctestsystem.util.MD5Util;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;

@Controller
@RequestMapping("/services")
public class LoginController {
    @Resource
    private UserInfoService userInfoService;
    @RequestMapping("login")
    public String login(){
        return "/services/login";
    }
    @RequestMapping("goLogin")
    public ModelAndView login(String username, String password, HttpSession session, String checkbox, HttpServletResponse response) {
        UserInfo user = new UserInfo();
        user.setEmail(username);
        user.setPassword(password);
        UserInfo loginUser = userInfoService.login(user);
        ModelAndView modelAndView=new ModelAndView();

        if (loginUser != null) {
            session.setAttribute("loginUser", loginUser);
            if (checkbox!=null){
                CookieUtil.addCookie("username",loginUser.getEmail(),"/",60*60*24*30,response);
                CookieUtil.addCookie("password", MD5Util.mymd5(loginUser.getPassword()),"/",60*60*24*30,response);
            }
            modelAndView.setViewName("/services/index");
            return modelAndView;
        } else {
            String err="0";
            modelAndView.addObject("err",err);
            modelAndView.setViewName("/services/login");
           return modelAndView;
        }


    }
    @RequestMapping("out")
    public String out(HttpSession session,HttpServletResponse response) {
        session.removeAttribute("loginUser");
        CookieUtil.addCookie("username","","/",0,response);
        CookieUtil.addCookie("password","","/",0,response);
        return "/services/login";
    }
}